package com.inwavetech.os.sync;

import com.inwavetech.os.entity.Os;
import com.inwavetech.os.entity.Product;
import com.inwavetech.os.util.DaoHelper;
import com.j256.ormlite.dao.CloseableIterator;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * Created by jgskin on 3/12/14.
 */
public class FinishedOsRemover {
    private final Dao<Os, ?> osDao;
    private final Dao<Product, ?> productDao;
    private final DaoHelper daoHelper;

    public FinishedOsRemover(DaoHelper daoHelper) {
        this.daoHelper = daoHelper;
        osDao = daoHelper.getDao(Os.class);
        productDao = daoHelper.getDao(Product.class);
    }

    public void execute() throws SQLException {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);

        long page = 0L;
        long limit = 30L;
        QueryBuilder<Os, ?> query = osDao.queryBuilder();
        query
            .limit(limit)
            .where().eq("status", Os.Status.FINISHED)
            .and().eq("send_to_server", false)
            .and().lt("finished_at", calendar.getTime());

        while (true) {
            long offset = page * limit;
            List<Os> oses = query.offset(page).query();

            if (oses.size() == 0) {
                break;
            }

            for (final Os os: oses) {
                TransactionManager.callInTransaction(daoHelper.getConnectionSource(), new Callable<Void>() {
                    @Override
                    public Void call() throws SQLException {
                        productDao.delete(os.products);
                        osDao.delete(os);

                        return null;
                    }
                });
            }

            page++;
        }
    }
}
